<?php
require_once 'Nine/Model.php';
class Models_Book extends Nine_Model
{
    protected $_primary = 'book_id';
    
    protected $_groupField = 'book_gid';
   
    public function __construct($config = array())
    {
        $this->_name = $this->_prefix . 'book';
        return parent::__construct($config); 
    }
    
    public function getAllBooks($condition = array(), $order = null, $count = null, $offset = null)
    {
        $select = $this->select()
                ->setIntegrityCheck(false)
                ->from(array('b' => $this->_name))
                ->join(array('l' => $this->_prefix . 'lang'), 'b.lang_id = l.lang_id', array('lname' => 'name', 'lang_image'))
                ->order($order)
                ->limit($count, $offset);
        if (null != @$condition['keyword']) {
    		$sql = "SELECT content_gid FROM {$this->_name} WHERE " . $this->getAdapter()->quoteInto('name LIKE ?', "%{$condition['keyword']}%");
    		$ids = $this->_db->fetchAll($sql);
    		if (empty($ids)) {
    			return array();
    		}
    		$idString = '';
    		foreach ($ids as $row) {
    			$idString .= $row['book_gid'] . ',';
    		}
    		/**
    		 * Add to select object
    		 */
    		$select->where('b.book_gid IN (' . trim($idString, ',') .')');
    	}
        return $this->fetchAll($select)->toArray();
    }
    
    public function getBookById($gid){
        $select = $this->select()
    			->where('book_id=?',$gid);
    	
    	return @reset($this->fetchAll($select)->toArray());
    }
    
    public function getBookByGid($gid){
        $select = $this->select()
    			->where('book_gid=?',$gid);
    	
    	return $this->fetchAll($select)->toArray();
    }
    
    
    public function getRootParent( $catGid )
    {
    	$select = $this->select()
    			->where("parent_id IS NULL AND 0 != LOCATE(?, CONCAT(',', gid_string, ','))", ",{$catGid},");
    			
    	return @reset($this->fetchAll($select)->toArray());
    }
    
    
	public function increaseSorting($startPos = 1, $num = 1)
    {
        $sql = "UPDATE {$this->_name} SET sorting = sorting + " . intval($num) . " WHERE sorting >= " . intval($startPos);
        
        $this->_db->query($sql);
    }
    
    
    public function updateGidString($gid, $gidString) 
    {
    	/**
    	 * Get current update node
    	 */
    	if (null == $gid) {
    		return;
    	}
    	else {
    		$category = @reset($this->getByColumns(array('book_gid = ?'	=>	$gid))->toArray());
    		$this->update(array('gid_string'	=> $this->concatGidString($category['gid_string'],$gidString)),array('book_gid = ?' => $gid));
    		return $this->updateGidString($category['parent_id'],$gidString);
    	}
    }
    
    public function deleteGidString($gid, $gidString)
    {
    	/**
    	 * Get current update node
    	 */
    	if (null == $gid){
    		return;
    	}
    	else {
    		$category = @reset($this->getByColumns(array('book_gid = ?'	=>	$gid))->toArray());
    		$this->update(array('gid_string' => $this->removeGidString($category['gid_string'],$gidString)), array('book_gid = ?' => $gid));
    		return $this->deleteGidString($category['parent_id'], $gidString);
    	}
    }
    
    
    private function concatGidString($oldGidStr, $concatGidStr) 
    {
    	if(null == $oldGidStr){
    		return $concatGidStr;
    	}
    	
    	$oldGidString = explode(',', trim($oldGidStr,','));
    	$concatGidString = explode(',', trim($concatGidStr,','));
    	
    	foreach($concatGidString as $item){
    		if (false == in_array($item, $oldGidString)){
    			$oldGidString[] = $item;
    		}
    	}
    	return implode(',', $oldGidString);
    }
    
    private function removeGidString($oldGidStr, $removedGidStr)
    {
    	if(null == $oldGidStr){
    		return null;
    	}
    	
    	$oldGidString = explode(',', trim($oldGidStr,','));
    	$removedGidString = explode(',', trim($removedGidStr,','));
    	
//    	echo "<pre>";print_r($removedGidString);die; 
    	foreach($oldGidString as $key => $item){
    		if (false != in_array($item, $removedGidString)){
    			unset($oldGidString[$key]);
    		}
    	}
//    	echo "<pre>";print_r($oldGidString);die; 
    	return implode(',', $oldGidString);
    }
}
?>
